<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区 -->
        <el-card>
            <!-- 搜索与添加区域 gutter:列与列之间的布局-->
            <el-row :gutter="15">
                <el-col :span="16">
                    <div class="grid-content bg-purple">
                        <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" clearable
                            @clear="getUserList">
                            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                        </el-input>
                    </div>
                </el-col>
                <el-col :span="4">
                    <div class="grid-content bg-purple">
                        <el-button type="primary" @click="callSubComp">添加用户</el-button>
                    </div>
                </el-col>
            </el-row>
            <!-- 用户列表区域 -->
            <el-table :data="userList" :border="true" stripe style="width: 100%;">
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="username" label="姓名" width="100" />
                <el-table-column prop="mobile" label="电话" width="120" />
                <el-table-column prop="email" label="邮箱地址" width="120" />
                <el-table-column prop="create_time" label="创建时间" width="120" />
                <el-table-column prop="role_name" label="角色" width="100" />
                <el-table-column label="当前用户状态" width="120">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="savaUserStatus(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <!-- 修改按钮 -->
                        <el-button type="primary" @click="callSubComp(scope.row)" icon="el-icon-edit"
                            size="mini">修改</el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" @click="delUserInfo(scope.row)" icon="el-icon-delete"
                            size="mini">删除</el-button>
                        <!-- 分配角色按钮 -->
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable='false'>
                            <el-button type="warning" icon="el-icon-setting" size="mini"
                                @click="setRole(scope.row)">分配角色</el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加、修改用户信息对话框 -->
        <edit-and-modify ref="refName"></edit-and-modify>
        <!-- 分配角色对话框 -->
        <el-dialog title="分配用户权限" :visible.sync="setRoleDialogVisible" width="50%" :close-on-click-modal="false">
            <div>
                <p>当前用户：{{ userInfo.username }}</p>
                <p>当前角色：{{ userInfo.role_name }}</p>
                <p>分配角色：</p>
                <el-select v-model="selectedRoldId" placeholder="请选择">
                    <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
                    </el-option>
                </el-select>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="setRoleConfirm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import editAndModify from './editAndModifyUser.vue' // 子组件引用
export default {
    created() {
        this.getUserList() // 获取用户信息列表
    },
    components: {
        editAndModify
    },
    data() {
        return {
            // 获取用户列表参数的对象
            queryInfo: {
                query: '',
                pagenum: 1,
                pagesize: 10
            },
            selectedRoldId: '', // 被选择的角色id
            userInfo: {}, // 用户信息
            roleList: [], // 角色列表数组
            userList: [], // 用户列表数组
            total: 0, // 总用户数
            setRoleDialogVisible: false, // 控制为用户分配角色对话框是否显示
        }
    },
    methods: {
        async getUserList() { // 获取用户列表
            const res = await this.$http.get('/users', { params: this.queryInfo })
            if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
            this.$message.success('获取用户列表成功')
            this.userList = res.data.users
            this.total = res.data.total
        },
        // 父组件调用子组件方法：添加用户信息
        callSubComp(row) {
            console.log(this.$refs.refName)
            this.$refs.refName.initData(row)
        },
        // 点击删除用户信息
        async delUserInfo(row) {
            // 写法1
            /*this.$confirm('是否删除该用户信息?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                console.log(row.id == 502);
                const res = await this.$http.delete(`users/${row.id}`, row.id)
                console.log(res);
                if (res.meta.status != 200) return this.$message.error('删除用户信息失败')
                this.$message.success('删除用户信息成功')
                this.getUserList()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            })*/

            // 写法2
            const result = await this.$confirm('是否删除该用户信息?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)

            if (result != 'confirm')
                return this.$message.info('已取消删除')
            console.log('确认删除');
            const res = await this.$http.delete(`users/${row.id}`, row.id)
            console.log(res);
            if (res.meta.status != 200) return this.$message.error('删除用户信息失败')
            this.$message.success('删除用户信息成功')
            this.getUserList()

        },
        // 监听pagesize改变事件
        async handleSizeChange(newSize) {
            this.queryInfo.pagesize = newSize // 更新每页数据条数参数
            this.getUserList()
            console.log('每页' + newSize + '条数据')
        },
        // 监听页面值改变事件
        async handleCurrentChange(newPage) {
            this.queryInfo.pagenum = newPage // 更新页码参数
            this.getUserList()
            console.log('当前位于第' + newPage + '页')
        },
        // 保存用户状态
        async savaUserStatus(userInfo) {
            const res = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
            if (res.meta.status != 200) {
                userInfo.mg_state = !userInfo.mg_state
                return this.$message.error('更新用户状态失败')
            }
            this.$message.success('更新用户状态成功')
        },
        async setRole(row) { // 分配角色显示对话框
            this.userInfo = row
            const res = await this.$http.get('/roles')
            if (res.meta.status != 200) return this.$message.error('获取角色列表失败')
            this.$message.success('获取角色列表成功')
            this.roleList = res.data
            this.setRoleDialogVisible = true
        },
        async setRoleConfirm() {
            if (!this.selectedRoldId) { // 是否选择了角色
                return this.$message.warning('请选择要分配的角色')
            }
            const res = await this.$http.put(`users/${this.userInfo.id}/role`, {
                rid: this.selectedRoldId
            })
            if (res.meta.status != 200)
                return this.$message.error('分配角色信息失败')
            this.$message.success('分配角色信息成功')
            this.getUserList()
            this.setRoleDialogVisible = false
        },


    }
}
</script>

<style>
.el-table {
    margin-top: 15px;
    font-size: 12px;
}

.el-pagination {
    margin-top: 15px;
}
</style>